package cn.gov.pbc.gd.credit.core.service.notice.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.service.impl.BaseServiceImpl;
import com.liu.tools.LogUtil;
import com.liu.tools.PrimaryUtil;
import com.liu.tools.StrUtil;

import cn.gov.pbc.gd.credit.api.corp.ICorpApi;
import cn.gov.pbc.gd.credit.api.inquiry.IInquiryApi;
import cn.gov.pbc.gd.credit.api.log.ILogInquiryApi;
import cn.gov.pbc.gd.credit.api.notice.INoticeApi;
import cn.gov.pbc.gd.credit.api.user.IUserApi;
import cn.gov.pbc.gd.credit.api.work.add.IAddApi;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.CommonConstant;
import cn.gov.pbc.gd.credit.common.model.UserModel;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.common.util.UserUtil;
import cn.gov.pbc.gd.credit.core.service.notice.INoticeService;
import cn.gov.pbc.gd.credit.vo.corp.CorpVo;
import cn.gov.pbc.gd.credit.vo.corp.ResCorpVo;
import cn.gov.pbc.gd.credit.vo.inquiry.InquiryVo;
import cn.gov.pbc.gd.credit.vo.log.LogInquiryVo;
import cn.gov.pbc.gd.credit.vo.notice.NoticeVo;
import cn.gov.pbc.gd.credit.vo.notice.ResNoticeVo;
import cn.gov.pbc.gd.credit.vo.user.UserVo;
import cn.gov.pbc.gd.credit.vo.work.add.AddVo;

@Service
public class NoticeServiceImpl extends BaseServiceImpl<ResNoticeVo, NoticeVo, INoticeApi> implements INoticeService{

	public Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);
	
	@Autowired
	private INoticeApi noticeApi;
	
	@Autowired
	private IUserApi userApi;
	
	@Autowired
	private ICorpApi corpApi;
	
	@Autowired
	private IInquiryApi inquiryApi;
	
	@Autowired
	private IRedisService redisService;
	
	@Autowired
	private ILogInquiryApi logInquiryApi;
	
	@Autowired
	private IAddApi addApi;
	
	@Override
	public ResultVo<PageListVo<ResNoticeVo>> page(NoticeVo record, PageListVo<ResNoticeVo> page,
			HttpServletRequest request) {
		
		UserModel userModel = UserUtil.getUserModel(record.getSid(), redisService);
		
		record.setCorpId(userModel.getCorpId());
		
		return super.page(record, page, request);
	}
	
	@Override
	public ResultVo<Map<String, Object>> totalForFristPage(NoticeVo vo, HttpServletRequest request) {
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		NoticeVo noticeVo = new NoticeVo();
		noticeVo.setCorpId(userModel.getCorpId());
		noticeVo.setNoticeFlag(0);
		noticeVo.setStatus(0);
		//未读信息统计
		Long waitReadTotal = noticeApi.count(noticeVo); 
		
		//待审批信息
		noticeVo.setStatus(null);		
		noticeVo.setApproveStatus(0);
		noticeVo.setNoticeFlag(1);		
		Long waitApproveTotal = noticeApi.count(noticeVo); 
		
		Map<String, Object> map = null;
		try {
			map = logInquiryApi.totalForPage(new LogInquiryVo());
		} catch (Exception e) {
			logger.error(LogUtil.msg("NoticeServiceImpl:totalForFristPage", "查询日志统计异常:" + JSON.toJSONString(vo)), e);
		}
		
		if(map == null){
			map = new HashMap<>();
		}
		
		map.put("waitReadTotal", waitReadTotal);
		map.put("waitApproveTotal", waitApproveTotal);
		

		ResultVo<Map<String, Object>> resultVo = new ResultVo<>();
		resultVo.setCode(CodeConstant.SUCCESS);
		resultVo.setData(map);
		
		return resultVo;
	}

	@Override
	public ResultVo<ResNoticeVo> approve(NoticeVo vo, HttpServletRequest request) {
		
		ResultVo<ResNoticeVo> resultVo = new ResultVo<>();
		if(vo == null || StrUtil.isNull(vo.getId()) || vo.getApproveStatus() == null){
			
			logger.error(LogUtil.msg("NoticeServiceImpl:approve", "请求参数不正确:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
			
		}
		
		ResNoticeVo resNoticeVo = noticeApi.queryById(vo.getId());
		
		if(resNoticeVo == null){
			logger.error(LogUtil.msg("NoticeServiceImpl:approve", "审批的数据不存在:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
			resultVo.setMsg("数据不存在");
			return resultVo;
		}
		
		if(resNoticeVo.getApproveStatus() != 0){
			logger.error(LogUtil.msg("NoticeServiceImpl:approve", "该事项已审批:" + JSON.toJSONString(resNoticeVo)));
			resultVo.setCode(CodeConstant.DATA_HAS_EXSIT);
			resultVo.setMsg("该事项已审批");
			return resultVo;
		}
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		//通知类型：0-新建用户，1-审批通过，2-审批失败，3-锁定，4-停用, 5-解锁待审批，6-启用待审批, 7-查询审批，8-报警通知
		int noticeType = resNoticeVo.getNoticeType();
		int approveStatus = vo.getApproveStatus();
		
		int flag = 1;
		
		int userStatus = approveStatus;
		int workAddStatus = approveStatus;
		String content = "";
		
		switch (noticeType) {
		case CommonConstant.NOTICE_TYPE_ADD_USER:
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "新增用户审批"));
			content = "新增用户审批成功";
			if(approveStatus == 2){
				content = "新增用户审批失败";
			}
		    break;
		case CommonConstant.NOTICE_TYPE_UNLOCK:
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "用户解锁审批"));
			content = "用户解锁审批成功";
			if(approveStatus == 2){
				content = "用户解锁审批失败";
			}
		    break;
		case CommonConstant.NOTICE_TYPE_UP:
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "用户启用审批"));
			content = "用户启用审批成功";
			if(approveStatus == 2){
				content = "用户启用审批失败";
			}
		    break;
		case CommonConstant.NOTICE_TYPE_ANEGT_INQUIRY:
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "代理信用查询审批"));
			content = "代理信用查询审批成功";
			if(approveStatus == 2){
				content = "信用查询审批失败";
			}
			flag = 2;
		    break;
		case CommonConstant.NOTICE_TYPE_JUSTICE_INQUIRY:
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "司法信用查询审批"));
			content = "司法查询审批成功";
			if(approveStatus == 2){
				content = "司法查询审批失败";
			}
			flag = 2;
		    break;
		case CommonConstant.NOTICE_TYPE_ADD_WORK:
			
			logger.info(LogUtil.msg("NoticeServiceImpl:approve", "加班申请审批"));
			content = "加班申请审批成功";
			workAddStatus = 2;
			if(approveStatus == 2){
				content = "加班申请审批失败";
				workAddStatus = 3;
			}
			
			flag = 3;
		    break;
		default:
			flag = 0;
			break;
		}
		noticeApi.update(vo);
		if(flag == 1){//用户审批
			
			UserVo userVo = new UserVo();
			userVo.setId(resNoticeVo.getSourceId());
			userVo.setApprovalTime(new Date());
			userVo.setApproverId(userModel.getUserId());
			userVo.setStatus(userStatus);
			
			try {
				
				userApi.updateApprove(userVo);	
			} catch (Exception e) {
				logger.error(LogUtil.msg("NoticeServiceImpl:approve", "审批数据异常:" + JSON.toJSONString(vo)));
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("审批数据异常");
				return resultVo;
			}
			
		}
		
		if(flag == 2){
			InquiryVo inquiryVo = new InquiryVo();
			inquiryVo.setId(resNoticeVo.getSourceId());
			inquiryVo.setApprovalTime(new Date());
			inquiryVo.setApproverId(userModel.getUserId());
			inquiryVo.setStatus(vo.getApproveStatus() == 2 ? 4 : 1);
			try {
				inquiryApi.update(inquiryVo);
			} catch (Exception e) {
				logger.error(LogUtil.msg("NoticeServiceImpl:approve", "审批数据异常:" + JSON.toJSONString(vo)));
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("审批数据异常");
				return resultVo;
			}
		}
		
		if(flag == 3){
			AddVo addVo = new AddVo();
			addVo.setId(resNoticeVo.getSourceId());
			addVo.setStatus(workAddStatus);
			addVo.setApproverId(userModel.getUserId());
			addVo.setApprovalTime(new Date());
			addVo.setNote(vo.getNote());
			try {
				addApi.update(addVo);
			} catch (Exception e) {
				logger.error(LogUtil.msg("NoticeServiceImpl:approve", "审批数据异常:" + JSON.toJSONString(vo)));
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("审批数据异常");
				return resultVo;
			}
		}
		
		CorpVo corpVo = new CorpVo();
		corpVo.setId(userModel.getCorpId());
		ResCorpVo resCorpVo = corpApi.query(corpVo);
		if(resCorpVo != null){
			
			if(! "-1".equals(resCorpVo.getParentId())){
				
			    NoticeVo noticeVo = new NoticeVo();
			    noticeVo.setId(PrimaryUtil.primaryId("R"));
			    noticeVo.setSourceId(resNoticeVo.getSourceId());
			    noticeVo.setNoticeType(noticeType);
				
			    noticeVo.setNoticeFlag(0);
			    noticeVo.setApproveStatus(1);
			    noticeVo.setStatus(0);
				
				noticeVo.setCorpId(resCorpVo.getParentId());
				noticeVo.setContent(content);
				noticeVo.setUpdateBy(userModel.getUserId());
				noticeVo.setUpdateTime(new Date());
				noticeVo.setCreateBy(userModel.getUserId());
				noticeVo.setCreateTime(new Date());
				
				noticeApi.insert(noticeVo);
			}
			
		}
		
		resultVo.setCode(CodeConstant.SUCCESS);
		
		return resultVo;
	}

	@Override
	public ResultVo<ResNoticeVo> findInfo(NoticeVo vo, HttpServletRequest request) {
		
		
		
		return null;
	}

	@Override
	public ResultVo<ResNoticeVo> read(NoticeVo vo, HttpServletRequest request) {
		
		ResultVo<ResNoticeVo> resultVo = new ResultVo<>();
		if(vo == null || StrUtil.isNull(vo.getId())){
			
			logger.error(LogUtil.msg("NoticeServiceImpl:approve", "请求参数不正确:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("请求参数不正确");
			return resultVo;
			
		}
		
		ResNoticeVo resNoticeVo = noticeApi.queryById(vo.getId());
		
		if(resNoticeVo == null){
			logger.error(LogUtil.msg("NoticeServiceImpl:read", "审批的数据不存在:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.DATA_NOT_EXSIT);
			resultVo.setMsg("数据不存在");
			return resultVo;
		}
		
		if(resNoticeVo.getStatus() != 0){
			logger.error(LogUtil.msg("NoticeServiceImpl:read", "该事项已阅读:" + JSON.toJSONString(resNoticeVo)));
			resultVo.setCode(CodeConstant.SUCCESS);
			return resultVo;
		}
		
		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		vo.setStatus(1);
		vo.setUpdateBy(userModel.getUserId());
		vo.setUpdateTime(new Date());
		try {
			noticeApi.update(vo);
		} catch (Exception e) {
			logger.error(LogUtil.msg("NoticeServiceImpl:read", "修改为已读异常:" + JSON.toJSONString(vo)));
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("修改数据异常");
			return resultVo;
		}
		
		resultVo.setCode(CodeConstant.SUCCESS);
		
		return resultVo;
	}

}
